﻿using System.Collections.Generic;
using System.Reflection;
using NsbExtensions.EndpointMetadata;
using NsbExtensions.Utilities;
using ObjectBuilder;

namespace NsbExtensions.Tests.Stubs
{
    public class TestMessagingEndpoint : MessagingEndpoint
    {
        private static readonly object _configLock = new object();
        private static bool _configured;
        public List<Assembly> RegisteredMessageHandlerAssemblies { get; set; }

        public List<IBackgroundService> PublicLocalServices
        {
            get { return LocalServices; }
        }

        protected override void RegisterMessagesAndHandlersIn(Assembly asm)
        {
            if (RegisteredMessageHandlerAssemblies == null)
                RegisteredMessageHandlerAssemblies = new List<Assembly>();

            RegisteredMessageHandlerAssemblies.Add(asm);
            ((TestBus) Bus).LoadMessageHandlersFrom(asm);
        }

        public static IMessagingEndpoint Create(IBuilder builder, params IBackgroundService[] localServices)
        {
            lock (_configLock)
            {
                if (!_configured)
                {
                    builder.ConfigureComponent(typeof (TestBus), ComponentCallModelEnum.Singleton);
                    builder.ConfigureComponent(typeof (TestSubscriptionStorage), ComponentCallModelEnum.Singleton);
                    builder.ConfigureComponent(typeof (TestTransport), ComponentCallModelEnum.Singleton);
                    builder.ConfigureComponent(typeof (EndpointDescription), ComponentCallModelEnum.Singleton)
                        .ConfigureProperty("EndpointID", "MyEndpointID")
                        .ConfigureProperty("Name", "MyEndpointName")
                        .ConfigureProperty("MessageBusAddress", "Test");

                    IComponentConfig epConfig = builder.ConfigureComponent(typeof (TestMessagingEndpoint),
                                                                           ComponentCallModelEnum.Singlecall)
                        .ConfigureProperty("LocalServices", new List<IBackgroundService>(localServices))
                        .ConfigureProperty("MessageHandlerAssemblies",
                                           new List<Assembly> {typeof (TestMessagingEndpoint).Assembly});
                    _configured = true;
                }
            }

            var endpoint = builder.Build<IMessagingEndpoint>();
            ((MessagingEndpoint) endpoint).Builder = builder;

            return endpoint;
        }
    }
}